import MySQLdb
import ConfigParser

class Database:
	def __init__(self):
		self.config = ConfigParser.RawConfigParser()
		if self.config.read("/etc/chopito/chopito.conf") != ['/etc/chopito/chopito.conf']:
			raise NameError, "Config not found"

		if not self.config.has_section('Database'):
			raise NameError, "Config file: Database not defined"

		self.db = None

	def _load_db(self):
		if self.db : # if previously attached
			try :
				self.db.ping() # test connection
			except MySQLdb.OperationalError, message: # loss of connection
				self.db = None # we lost database connection

		if self.db is None : # if no valid database handle
			if self.config.get('Database', 'type') == "mysql":
				self.db = MySQLdb.connect(host=self.config.get('Database','host'),
							  user=self.config.get('Database','user'),
							  passwd=self.config.get('Database','pass'),
							  db=self.config.get('Database','database'))
	def cursor_tuple(self):
		self._load_db()
		return self.db.cursor()

	def cursor_dict(self):
		self._load_db()
		return self.db.cursor(MySQLdb.cursors.DictCursor)

	def execute(self, sql, restype="dict"):
		if restype == "dict":
			cursor = self.cursor_dict()
		else:
			cursor = self.cursor_tuple()

		cursor.execute(sql)
		res = cursor.fetchall()
		if sql.lower().find('insert') != -1 or sql.lower().find('update') != -1:
			self.db.commit()
		cursor.close()
		self.close()

		return res

	def commit(self):
		self._load_db()
		self.db.commit()
	
	def close(self):
		self.db.close()
		self.db = None
